#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
bool cmp(long long A, long long B) {
    return A > B;
}
class Solution {
public:

    long long bfs(TreeNode* root, int k) {
        queue<TreeNode*> q;
        q.push(root);
        int cnt = 0;
        vector<long long> ans;

        while (!q.empty()) {
            int sz = q.size();
            long long s = 0;
            for (int i = 0; i < sz; i++) {
                TreeNode* t = q.front();
                q.pop();
                s += t->val;

                if (t->left)q.push(t->left);
                if (t->right)q.push(t->right);
            }
            //cout<<s<<endl;
            ans.push_back(s);
        }
        // cout<<ans.size()<<endl;
        if (ans.size() < k)return -1;
        sort(ans.begin(), ans.end(), cmp);
        return ans[k - 1];
    }
    long long kthLargestLevelSum(TreeNode* root, int k) {
        return bfs(root, k);
    }
};